package org.batch.config.batch.processor;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import org.batch.config.batch.validator.TradingValidator;
import org.batch.entity.Trading;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.validator.ValidatingItemProcessor;
import org.springframework.batch.item.validator.ValidationException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 注册ItemProcessor
 * 进行数据处理 + 数据校验
 *
 * @author LiKun
 * @date 2021/9/27 16:40
 */
@Component
public class TradingProcessor extends ValidatingItemProcessor<Trading> {
    private static final Logger logger = LoggerFactory.getLogger(TradingProcessor.class);

    @Resource
    private Snowflake snowflake;
    @Resource
    private TradingValidator tradingValidator;

    @PostConstruct
    public void initialize() {
        logger.info("加载数据处理/校验类：TradingProcessor");
        this.setValidator(tradingValidator);
    }

    @Override
    public Trading process(Trading item) throws ValidationException {
        // 调用父类的process方法进行数据校验
        super.process(item);
        if (StrUtil.isEmpty(item.getId())) {
            item.setId(snowflake.nextIdStr());
            logger.info("数据添加ID成功：{}", item);
        }
        logger.info("数据处理成功：{}", item);

        return item;
    }
}
